/** \file qQWWMainWindow.cpp
 * \brief QWordWizard main window implementation
 */

#include "qwwmainwindow.h"
#include "qwwabout.h"
#include "qwwsettings.h"
#include "qwwdic.h"
#include <QSettings>
#include <vector>

static vector<pair<bool, QString> > dic;
static QString loading_error_str = QObject::tr("Dictionary loading error. Go to \"Settings->Dictionary\" and solve it.");
static QString no_data_str = QObject::tr("No dictionary loaded or used. Go to \"Settings->Dictionary\" and load or set used flag.");

QWWMainWindow::QWWMainWindow(QWidget *parent, Qt::WindowFlags f):
    mp_menu(new QWWMenu(this)),
    mp_timer(new QTimer())
{
    setParent(parent);
    setWindowTitle("QWordWizard");
    setWindowIcon(*mp_menu->mp_active_icon);
    setWindowFlags(f | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    setGeometry(0, 0, 500, 40);
    setAlignment(Qt::AlignCenter);
    setReadOnly(true);

    ReadSettings();

    connect(mp_menu->mp_show_hide_action.get(), SIGNAL(triggered()), this, SLOT(ShowHide()));
    connect(mp_menu->mp_tray.get(), SIGNAL(activated (QSystemTrayIcon::ActivationReason)), this, SLOT(ShowHide(QSystemTrayIcon::ActivationReason)));
    connect(mp_menu->mp_move_freeze_action.get(), SIGNAL(triggered()), this, SLOT(MoveFreeze()));
    connect(mp_menu->mp_about_action.get(), SIGNAL(triggered()), this, SLOT(ShowAbout()));
    connect(mp_menu->mp_settings_action.get(), SIGNAL(triggered()), this, SLOT(ShowSettings()));
    connect(mp_menu->mp_quit_action.get(), SIGNAL(triggered()), this, SLOT(close()));

    connect(mp_timer.get(), SIGNAL(timeout()), this, SLOT(UpdateLabel()));

    QWWDic *p = QWWDic::Instance();
    if (!p->Reload())
    {
        mp_timer->stop();
        setText(loading_error_str);
    }
    else
    {
        UpdateLabel();
    }
}

QWWMainWindow::~QWWMainWindow()
{
    WriteSettings();
}

void QWWMainWindow::ShowAbout()
{
    QWWAbout about;
    about.exec();
}

void QWWMainWindow::ReadSettings()
{
    QSettings settings("Education", "QWordWizard");
	QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
	QSize size = settings.value("size", QSize(500, 40)).toSize();
	m_interval = settings.value("interval", 30).toInt();
	resize(size);
	move(pos);

    QWWDic *p = QWWDic::Instance();

    int len = settings.beginReadArray("dic");
    for (int i = 0; i < len; ++i)
    {
        settings.setArrayIndex(i);
        bool used = settings.value("used").toBool();
        QString filename = settings.value("filename").toString();
        p->Add(used, filename);
    }
    settings.endArray();

    mp_timer->start(m_interval * 1000);
}

void QWWMainWindow::WriteSettings()
{
	QSettings settings("Education", "QWordWizard");
	settings.setValue("pos", pos());
	settings.setValue("size", size());
	settings.setValue("interval", m_interval);

    QWWDic_attr_t dic;
    QWWDic *p = QWWDic::Instance();
    p->GetDictionariesAttr(dic);

    settings.beginWriteArray("dic");
  
    for (int i = 0; i < (int)dic.size(); ++i)
    {
        settings.setArrayIndex(i);
        settings.setValue("used", dic.at(i).first);
        settings.setValue("filename", dic.at(i).second);
    }
    settings.endArray();
}

void QWWMainWindow::ShowSettings()
{
    QWWSettings settings;

    QWWDic_attr_t dic;
    QWWDic *p = QWWDic::Instance();
    p->GetDictionariesAttr(dic);

    settings.SetDictionaries(dic);
    settings.SetInterval(m_interval);

    if (settings.exec() == QDialog::Rejected)
        return;

    m_interval = settings.GetInterval();
    settings.GetDictionaries(dic);
    p->Clear();
    for(QWWDic_attr_t::iterator it = dic.begin(); it != dic.end(); ++it)
        p->Add(it->first, it->second);
    WriteSettings();

    if (!p->Reload())
    {
        mp_timer->stop();
        setText(loading_error_str);
    }
    else
    {
        UpdateLabel();
        mp_timer->start(m_interval * 1000);
    }
}

void QWWMainWindow::ShowHide(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
	{
		case QSystemTrayIcon::Trigger:
			if (isVisible())
			{
				mp_menu->mp_show_hide_action->setText(tr("Show"));
				mp_menu->mp_move_freeze_action->setEnabled(false);
				mp_menu->mp_tray->setIcon(*mp_menu->mp_inactive_icon);
				hide();
			}
			else
			{
				mp_menu->mp_show_hide_action->setText(tr("Hide"));
				mp_menu->mp_move_freeze_action->setEnabled(true);
				mp_menu->mp_tray->setIcon(*mp_menu->mp_active_icon);
				show();
			}
			break;
		default:
			break;
	}
}

void QWWMainWindow::MoveFreeze()
{
    if (windowFlags() & Qt::FramelessWindowHint)
	{
                setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
		mp_menu->mp_move_freeze_action->setText(tr("Freeze"));
		show();
	}
	else
	{
                setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
		mp_menu->mp_move_freeze_action->setText(tr("Move"));
		show();
	}
}

void QWWMainWindow::UpdateLabel()
{
    QWWDic_data_t data;
    QWWDic *p = QWWDic::Instance();
    p->GetData(data);

    if (!data.first.isEmpty() && !data.second.isEmpty())
        setHtml("<font color=\"red\">" + data.first + "</font>:		" + data.second);
    else
        setText(no_data_str);
}
